<template>
  <v-form ref="form" v-model="form.valid" class="signup">
    <v-container class="contain">
      <div class="view">
        <v-row align="center" class="mt-3">
          <v-col cols="12">
            <h2>{{ isEdit ? $t('newvip1') : $t('newvip') }}</h2>
          </v-col>
        </v-row>
        <v-divider class="my-3" />
        <v-row align="center" style="margin-top: 12px">
          <v-col cols="12" sm="4">
            <span class="title-text">
              {{ $t('name') }}
            </span>
            <span class="red--text"> * </span>
          </v-col>
          <v-col cols="8" sm="4">
            <v-text-field
              v-model="form.entry_name_one"
              dense
              :rules="nameRules"
              :counter="50"
              :maxlength="50"
              :label="$t('firstname')"
              required
              outlined
              persistent-hint
            />
          </v-col>
          <v-col cols="8" sm="4">
            <v-text-field
              v-model="form.entry_name_two"
              dense
              :rules="nameRules"
              :counter="50"
              :maxlength="50"
              :label="$t('lastname')"
              required
              outlined
              persistent-hint
            />
          </v-col>
        </v-row>
        <v-row align="center">
          <v-col cols="12" sm="4">
            <span class="title-text">
              {{ $t('email') }}
            </span>
            <span class="red--text"> * </span>
          </v-col>

          <v-col cols="12" sm="8" class="email-col">
            <v-text-field
              v-model="form.email"
              dense
              :rules="emailRules"
              :label="$t('email')"
              type="phone"
              required
              outlined
              persistent-hint
              :disabled="pending || isEdit"
              style="margin-right: 8px"
            />
            <v-btn
              v-if="!isEdit"
              variant="text"
              :disabled="!form.email || pending"
              style="margin-top: 3px"
              @click="send"
            >
              {{ pending ? intervaltime : $t('sendVerificationCode') }}
            </v-btn>
          </v-col>
        </v-row>
        <v-row v-if="$route.query.type !== 'edit'" align="center">
          <v-col cols="12" sm="4">
            <span class="title-text">
              {{ $t('code') }}
            </span>
            <span class="red--text"> * </span>
          </v-col>

          <v-col cols="12" sm="8">
            <v-otp-input v-model="form.email_code" :rules="codeRules" length="6" type="number" />
            <span class="tip--text">{{ $t('verificationCodeTip') }}</span>
          </v-col>
        </v-row>

        <v-row v-if="!isEdit" align="center">
          <v-col cols="12" sm="4">
            <span class="title-text">
              {{ $t('password') }}
            </span>
            <span class="red--text"> * </span>
          </v-col>
          <v-col cols="12" sm="8">
            <v-text-field
              v-model="form.password"
              dense
              type="password"
              autocomplete="off"
              :rules="passwordRules"
              :counter="20"
              :maxlength="20"
              :label="$t('password')"
              required
              outlined
              persistent-hint
            />
            <span class="tip--text">{{ $t('passwordTips') }}</span>
          </v-col>
        </v-row>
        <v-row align="center">
          <v-col cols="12" sm="4">
            <span class="title-text">
              {{ $t('birthday') }}
            </span>
            <span class="red--text"> * </span>
          </v-col>

          <v-col cols="12" sm="8">
            <div style="position: relative">
              <v-text-field
                v-model="form.birthday"
                dense
                class="special-input"
                style="width: 210px; height: 50px"
                :rules="permit_dateRules"
                label=" "
                required
                outlined
                persistent-hint
              />
              <date-picker
                v-model="form.birthday"
                style="position: absolute; left: 0; top: 0"
                :rules="permit_dateRules"
                type="date"
                value-type="format"
                format="YYYY-MM-DD"
              />
            </div>
          </v-col>
        </v-row>
        <v-row align="center">
          <v-col cols="12" sm="4">
            <span class="title-text">
              {{ $t('country') }}
            </span>
            <span class="red--text"> * </span>
          </v-col>

          <v-col cols="12" sm="8">
            <v-combobox
              dense
              :items="countries_codeList"
              item-text="name"
              item-value="code"
              :value="getCountry(form.countries_code)"
              :rules="permit_noRules"
              :label="$t('country')"
              required
              outlined
              persistent-hint
              @input="handleCountriesCodeChange"
            />
          </v-col>
        </v-row>

        <v-row align="center">
          <v-col cols="12" sm="4">
            <span class="title-text">
              {{ $t('phone') }}
            </span>
            <span class="red--text"> * </span>
          </v-col>
          <v-col cols="6" sm="2">
            <v-text-field
              v-model="form.mobile_code"
              dense
              :rules="mobileCodeRules"
              :label="$t('areaCode')"
              required
              :counter="4"
              :maxlength="4"
              outlined
              persistent-hint
            >
              <template #prepend-inner>
                <span class="area_code_icon">+</span>
              </template>
            </v-text-field>
          </v-col>
          <v-col cols="6" sm="6">
            <v-text-field
              v-model="form.mobile"
              dense
              :rules="mobileRules"
              :label="$t('phone')"
              required
              :counter="14"
              :maxlength="14"
              outlined
              persistent-hint
            />
          </v-col>
        </v-row>
        <v-row align="center">
          <v-col cols="12" sm="4">
            <span class="title-text">
              {{ $t('sex') }}
            </span>
            <span class="red--text"> * </span>
          </v-col>

          <v-col cols="12" sm="8">
            <v-select
              v-model="form.gender"
              dense
              :items="[
                { label: $t('female'), value: 2 },
                { label: $t('male'), value: 1 }
              ]"
              item-text="label"
              item-value="value"
              :rules="permit_noRules"
              :label="$t('sex')"
              required
              outlined
              persistent-hint
            />
          </v-col>
        </v-row>
        <v-row align="center">
          <v-col cols="12" sm="4">
            <span class="title-text">
              {{ $t('city') }}
            </span>
          </v-col>

          <v-col cols="12" sm="8">
            <v-text-field
              v-model="form.city"
              dense
              :label="$t('city')"
              :counter="200"
              :maxlength="200"
              required
              outlined
              persistent-hint
            />
          </v-col>
        </v-row>
        <v-row align="center">
          <v-col cols="12" sm="4">
            <span class="title-text">
              {{ $t('address') }}
            </span>
          </v-col>

          <v-col cols="12" sm="8">
            <v-text-field
              v-model="form.address"
              dense
              :label="$t('address')"
              :counter="200"
              :maxlength="200"
              required
              outlined
              persistent-hint
            />
          </v-col>
        </v-row>

        <v-row align="center">
          <v-col cols="12" sm="4">
            <span class="title-text">
              {{ $t('drivelicense') }}
            </span>
            <span class="red--text"> * </span>
          </v-col>

          <v-col cols="12" sm="8">
            <v-select
              v-model="form.permit_type"
              :style="{ fontSize: '10px', color: 'blue' }"
              dense
              :items="permit_typeList"
              item-text="name"
              item-value="id"
              :rules="permitRules"
              :label="$t('drivelicense')"
              required
              outlined
              persistent-hint
            />
          </v-col>
        </v-row>
        <v-row align="center">
          <v-col cols="12" sm="4">
            <span class="title-text">
              {{ $t('drivelicenseno') }}
            </span>
            <span class="red--text"> * </span>
          </v-col>

          <v-col cols="12" sm="8">
            <v-text-field
              v-model="form.permit_no"
              dense
              :rules="permit_noRules"
              :label="$t('drivelicenseno')"
              :counter="200"
              :maxlength="200"
              required
              outlined
              persistent-hint
            />
          </v-col>
        </v-row>
        <v-row align="center">
          <v-col cols="12" sm="4">
            <span class="title-text">
              {{ $t('drivelicensedate') }}
            </span>
            <span class="red--text"> * </span>
          </v-col>

          <v-col cols="12" sm="8">
            <div style="position: relative">
              <v-text-field
                v-model="form.permit_date"
                dense
                class="special-input"
                style="width: 210px; height: 32px"
                :rules="permit_dateRules"
                label=" "
                required
                outlined
                persistent-hint
              />
              <date-picker
                v-model="form.permit_date"
                style="position: absolute; left: 0; top: 0"
                :rules="permit_dateRules"
                value-type="format"
                format="YYYY-MM-DD"
              />
            </div>
          </v-col>
        </v-row>
        <v-row align="center">
          <v-col cols="12" sm="4">
            <span class="title-text">
              {{ $t('passportno') }}
            </span>
          </v-col>

          <v-col cols="12" sm="8">
            <v-text-field
              v-model="form.passport"
              dense
              :label="$t('passportno')"
              :counter="200"
              :maxlength="200"
              required
              outlined
              persistent-hint
            />
          </v-col>
        </v-row>
        <v-row align="center" justify="center" class="mb-4">
          {{ $t('rule') }}
          <a text style="margin-left: 4px" class="blue--text text--lighten-3" @click="gotorule">
            {{ $t('rule1') }}
          </a>
        </v-row>
        <v-row align="center" justify="center" class="mb-4">
          <div class="bottom_check_box">
            <v-checkbox v-model="sendemail" style="font-size: 10px" />
            <span>{{ $t('sendemail') }}</span>
          </div>
        </v-row>
        <v-row no-gutters align="center" justify="center">
          <v-btn
            class="mr-2"
            elevation="2"
            rounded
            dark
            style="text-transform: none"
            @click="$router.back()"
          >
            {{ $route.query.type === 'edit' ? $t('cancel') : $t('noagree') }}
          </v-btn>
          <v-btn
            elevation="2"
            rounded
            dark
            color="#E22129FF"
            :disabled="!sendemail"
            style="text-transform: none"
            @click="signUp"
          >
            {{ $route.query.type === 'edit' ? $t('submit') : $t('agree') }}
          </v-btn>
        </v-row>
      </div>
      <v-snackbar v-model="snackbar" centered timeout="3000">
        {{ $t('ok') }}
      </v-snackbar>
      <v-snackbar v-model="tipShow" centered timeout="3000">
        {{ tipTxt }}
      </v-snackbar>
      <v-dialog v-model="dialog" width="80%">
        <div style="background: #fff; padding: 16px">
          <!-- <Rule /> -->
          <v-card-actions>
            <v-btn depressed color="error" @click="dialog = false">
              {{ $t('accept') }}
            </v-btn>
          </v-card-actions>
        </div>
      </v-dialog>
    </v-container>
  </v-form>
</template>

<script>
import DatePicker from 'vue2-datepicker';
import 'vue2-datepicker/index.css';
import { mapMutations } from 'vuex';
import { countries } from '~/utils/countries';

const SIGNUP_FORM_DATA = 'SIGNUP_FORM_DATA';

export default {
  name: 'SignUp',
  components: {
    DatePicker
  },
  data() {
    return {
      valid: false,
      snackbar: false,
      form: {
        id: '',
        gender: '',
        entry_name_one: '',
        entry_name_two: '',
        password: '',
        countries_code: '',
        zip_code: '',
        address: '',
        company_name: '',
        email: '',
        mobile: '',
        mobile_code: '',
        birthday: '',
        email_code: '',
        province: '', // 都道县列表接口
        city: '',
        district: '',
        career: 1, // "职业列表接口",
        permit_type: 1, // "驾驶证类型接口",
        permit_no: '',
        permit_date: '', // 驾驶证日期
        passport: '',
        sendemail: false
      },
      imgsrc: 'https://jvqzgvrcum.only-jdm.com/api/zuche/user/captcha?r=' + new Date().getTime(),
      intervaltime: 59,
      pending: false,
      showcode: false,
      hasphone: false,
      tipShow: false,
      tipTxt: '',
      nameRules: [
        (v) => !!v || this.$t('require')
        // (v) => v.length <= 20 || this.$t("namenomore"),
      ],
      addressRules: [(v) => !!v || this.$t('require')],
      company_nameRules: [(v) => !!v || this.$t('require')],
      passwordRules: [(v) => !!v || this.$t('require')],
      permitRules: [(v) => !!v || this.$t('require')],
      permit_noRules: [(v) => !!v || this.$t('require')],
      permit_dateRules: [(v) => !!v || this.$t('require')],
      captcha_codeRules: [(v) => !!v || this.$t('require')],
      emailRules: [
        (v) => !!v || this.$t('require'),
        (v) => /.+@.+/.test(v) || this.$t('emialrule')
      ],
      codeRules: [(v) => !!v || this.$t('require')],
      mobileCodeRules: [
        (v) => !!v || this.$t('require'),
        (v) => /^\d+$/.test(v) || this.$t('mobilerule')
      ],
      mobileRules: [
        (v) => !!v || this.$t('require'),
        (v) => /^\d+$/.test(v) || this.$t('mobilerule')
      ],
      birthdayRules: [(v) => !!v || this.$t('require')],
      countries_codeList: [],
      ProvinceList: [],
      careerList: [],
      permit_typeList: [],
      dialog: false,
      isEdit: false,
      permit_sendemailRules: [(v) => !!v || this.$t('require')],
      sendemail: false
    };
  },
  mounted() {
    this.$api
      .post('/home/getCountriesList', {
        //
      })
      .then((res) => {
        this.countries_codeList = res;
        this.autoSetCountryInfo();
      });
    this.$api
      .post('/home/getProvinceList', {
        //
      })
      .then((res) => {
        this.ProvinceList = res;
      });
    this.$api
      .post('/home/getCareerList', {
        //
      })
      .then((res) => {
        this.careerList = res;
      });
    this.$api
      .post('/home/getPermitTypeList', {
        //
      })
      .then((res) => {
        this.permit_typeList = res;
      });
    if (this.$route.query.type === 'edit') {
      this.$api.post('/user/getInfo', {}).then((res) => {
        this.form = res;
      });
    } else {
      const storeDataStr = sessionStorage.getItem(SIGNUP_FORM_DATA);
      if (storeDataStr) {
        this.form = {
          ...this.form,
          ...JSON.parse(storeDataStr)
        };
      }
    }
    const type = this.$route.query.type;
    this.isEdit = type && type === 'edit';
    console.log('进入页面类型', this.type);
    console.log('form', this.form);
  },
  beforeDestroy() {
    if (this.$route.query.type !== 'edit') {
      sessionStorage.setItem(SIGNUP_FORM_DATA, JSON.stringify(this.form));
    }
  },
  methods: {
    ...mapMutations(['setLogin']),
    autoSetCountryInfo() {
      if (this.form.countries_code) return;
      const currentLanguage = navigator.language;
      const currentCountry = countries.find((item) => item.language === currentLanguage);
      if (!currentCountry) return;
      const country = this.countries_codeList.find((item) => item.code === currentCountry.code);
      if (!country) return;
      this.form.countries_code = country.code;
      this.form.mobile_code = country.mobile_code;
    },
    getCountry(code) {
      return this.countries_codeList.find((item) => item.code === code) || code;
    },
    handleCountriesCodeChange(country) {
      this.form.countries_code = country.code;
      this.form.mobile_code = country.mobile_code;
    },
    send() {
      this.pending = true;
      this.showcode = true;
      const time = setInterval(() => {
        this.intervaltime--;
        if (this.intervaltime <= 0) {
          this.pending = false;
          this.intervaltime = 59;
          clearInterval(time);
        }
      }, 1000);
      this.$api.post('/user/sendRegisterEmailCode', this.form, { getAll: true }).then((res) => {
        if (res.code === 1) {
          console.log('发送成功');
          this.tipTxt = this.$t('sendsuccess');
          this.tipShow = true;
        } else {
          this.tipTxt = res.msg;
          this.tipShow = true;
          this.pending = false;
        }
      });
    },
    changeimgSrc() {
      this.imgsrc =
        'https://jvqzgvrcum.only-jdm.com/api/zuche/user/captcha?r=' + new Date().getTime();
    },
    gotorule() {
      // window.open(
      //     `/h5/rule`,
      //     '_blank',
      // )
      // this.dialog=true
    },
    signUp() {
      const valid = this.$refs.form.validate();
      if (valid) {
        if (this.$route.query.type === 'edit') {
          this.$api.post('/user/edit', this.form, { getAll: true }).then((res) => {
            if (res.code === 1) {
              this.snackbar = true;
              setTimeout(() => {
                this.snackbar = false;
              }, 2000);
            }
          });
          return;
        }
        this.$api.post('/user/register', this.form, { getAll: true }).then((res) => {
          if (res.code === 1) {
            this.setLogin(true);
            this.snackbar = true;
            sessionStorage.removeItem(SIGNUP_FORM_DATA);
            setTimeout(() => {
              this.$router.push(this.localePath('/registered'));
            }, 2000);
          }
        });
      }
    }
  }
};
</script>

<style scoped lang="scss">
@media screen and (max-width: 600px) {
  .contain {
    .view {
      width: 80vw !important;
    }
  }
  .email-col {
    display: unset !important;
  }
}

.email-col {
  display: flex;
}

.theme--dark.v-btn.v-btn--disabled.v-btn--has-bg {
  background-color: rgb(226, 33, 41, 0.5) !important;
  border-color: rgb(226, 33, 41, 0.5) !important;
}
.contain {
  display: flex;
  align-items: center;
  justify-content: center;

  .view {
    width: 52vw;
    max-width: 1000px;
  }
}
</style>
<style lang="scss">
.special-input {
  position: relative;
  .v-input__control {
    min-height: 32px !important;
  }
  .v-input__slot {
    min-height: 32px !important;
  }
}
.title-text {
  font-weight: bold;
}
.tip--text {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.6);
}
.v-select-item .vs__dropdown-option {
  font-size: 10px; /* 设置字体大小 */
  color: blue; /* 设置字体颜色 */
}
.bottom_check_box {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.signup {
  .v-text-field__details {
    min-height: unset;
    margin-bottom: 0 !important;
  }
  .v-messages {
    min-height: unset !important;
  }
  .v-input__slot {
    margin-bottom: 0 !important;
  }
  .col-12 {
    padding: 8px !important;
  }
  .v-input--selection-controls {
    margin-top: 0 !important;
  }
}
.area_code_icon {
  margin-top: 6px;
  font-size: 14px;
}
</style>
